import Vue from "vue";
import $ from "jquery";

import { central, peripheral } from "../hos/ble.js";

import { Activity } from "./activity.js";


class BleHelper extends Activity {

    /**
     * 将10进制数组转16进制字符串
     * str:字符串 [0,240,0,0,0,0]
     * arr:返回数组 "00f001000000"
     */
    static dec2hex(arr) {
        let str = "";
        arr.map(function (item) {
            if (typeof item == "number") {
                if (item <= 0x0f) {
                    str += "0" + item.toString(16);
                } else {
                    str += item.toString(16);
                }
            }
        });
        return str;
    }

    onCreate() {
        super.onCreate();

        this.myPeripheral = null;

        new Vue({
            el: this.find("scan"),
            methods: {
                click: () => {
                    central.scan();
                }
            }
        });

        new Vue({
            el: this.find("stopscan"),
            methods: {
                click: () => {
                    // peripheral.writeValue(this.myPeripheral, "FEE7", "FEC7", "fafba20101000001a5")
                    central.stopScan();
                }
            }
        });

        new Vue({
            el: this.find("write"),
            methods: {
                click: () => {
                    if (!this.myPeripheral) {
                        alert("设备未连接");
                        return;
                    }
                    // 深圳跑步机
                    // peripheral.writeValue(this.myPeripheral, "FEE7", "FEC7", "fafda20101000001a5")
                    // 深圳手环 HBM_B3
                    var value = [0xa1, 0x01, 0x01];
                    let checksum = 0;
                    for (let i = 2; i < value.length; i++) {
                        checksum ^= value[i];
                    }
                    value.push(checksum);
                    var hex = BleHelper.dec2hex(value);
                    $(this.find("log")).append("发送数据" + hex + "<br>");
                    peripheral.writeValue(this.myPeripheral, "0001", "0002", hex);
                }
            }
        });

        var peripherals = [];
        var peripheralAll = central.peripherals();

        for (let i in peripheralAll) {
            if (peripheralAll[i].name == "HBM_B3") {
                peripherals.push(peripheralAll[i]);
                break;
            }
        }
        var retrieveConnected = central.retrieveConnected(["0001"]);
        $(this.find("log")).append("系统已连接" + JSON.stringify(retrieveConnected) + "<br>");
        for (let i in retrieveConnected) {
            // if (true) {
            if (retrieveConnected[i].name == "HBM_B3") { // 只显示手环
                var exit = false;
                for (let i in peripherals) {
                    if (peripherals[i].uuid == retrieveConnected[i].uuid) {
                        exit = true;
                        break;
                    }
                }
                if (!exit) {
                    peripherals.push(retrieveConnected[i]);
                }
                break;
            }
        }

        this.vm = new Vue({
            el: this.find("devices"),
            data: {
                items: peripherals
            },
            methods: {
                connect: (aPeripheral) => {
                    this.uninitMyPeripheral();
                    this.myPeripheral = aPeripheral;
                    this.initMyPeripheral();
                    central.connect(this.myPeripheral);
                },
                cancelConnect: (aPeripheral) => {
                    central.cancelAllConnect();
                    // central.cancelConnect(this.myPeripheral)
                }
            }
        });
        $(this.find("log")).append("蓝牙:" + (central.isPoweredOn() ? "开" : "关") + "<br>");
    }

    stateObserver(event) {
        if (event.data.state != "poweredOn") {
            let items = this.vm.items;
            // 清空蓝牙列表
            items.splice(0, items.length);
        }
        $(this.find("log")).append("蓝牙状态:" + event.data.state + "<br>");
    }

    discoverObserver(event) {
        let items = this.vm.items;
        for (let i in items) {
            if (items[i].uuid == event.data.uuid) { return; }
        }
        $(this.find("log")).append("发现设备:" + event.data.name + "<br>");
        if (event.data.name != "HBM_B3") { return; }
        this.vm.items.push(event.data);
    }

    connectObserver(event) {
        $(this.find("log")).append(event.data.name + "连接成功" + "<br>");
        if (!this.myPeripheral || event.data.uuid != this.myPeripheral.uuid) {
            // 不是自己需要操作的设备，走
            return;
        }
        // 扫描读写服务
        peripheral.discoverServices(this.myPeripheral);
    }

    disconnectObserver(event) {
        $(this.find("log")).append(event.data.name + "断开连接" + "<br>");
    }

    discoverServicesObserver(event) {
        let services = event.data.services;
        $(this.find("log")).append(this.myPeripheral.name + "发现服务" + JSON.stringify(services) + "<br>");
        for (let i in services) {
            peripheral.discoverCharacteristics(this.myPeripheral, services[i]);
            // if(services[i] == "FEE7") {
            //     peripheral.discoverCharacteristics(this.myPeripheral, services[i], ["FEC9", "FEC7"])
            // }
        }
    }

    discoverCharacteristicsObserver(event) {
        alert(JSON.stringify(event));
        let service = event.data.service;
        let characteristics = event.data.characteristics;
        $(this.find("log")).append(this.myPeripheral.name + "发现特征" + JSON.stringify(characteristics) +
            "在服务" + service + "<br>");
        if (service == "FEE7") {
            for (let i in characteristics) {
                if (characteristics[i] == "FEC8") {
                    // 设置之后才能收到外设的通知
                    peripheral.setNotifyValue(this.myPeripheral, service, characteristics[i], true);
                    break;
                }
            }
        } else if (service == "0001") {
            // 深圳的手环 服务0001 通知特征0003 写特征0002
            for (let i in characteristics) {
                if (characteristics[i] == "0003") {
                    // 设置之后才能收到外设的通知
                    peripheral.setNotifyValue(this.myPeripheral, service, characteristics[i], true);
                    break;
                }
            }
        }
    }

    updateValueObserver(event) {
        let value = event.data.value;
        $(this.find("log")).append(this.myPeripheral.name + "收到通知" + value + "<br>");
        // 收到什么回传什么
        // peripheral.writeValue(this.myPeripheral, "18F0", "2AF1", value)
        // 发送字符串
        // peripheral.writeStringValue(this.myPeripheral, "18F0", "2AF1", "🌹😊\r\n")
    }

    initMyPeripheral() {
        peripheral.addDiscoverServicesObserver(this.myPeripheral, this, this.discoverServicesObserver);
        peripheral.addDiscoverCharacteristicsObserver(this.myPeripheral, this, this.discoverCharacteristicsObserver);
        peripheral.addUpdateValueObserver(this.myPeripheral, this, this.updateValueObserver);
    }

    uninitMyPeripheral() {
        if (!this.myPeripheral) {
            return;
        }
        peripheral.removeDiscoverServicesObserver(this.myPeripheral, this.discoverServicesObserver);
        peripheral.removeDiscoverCharacteristicsObserver(this.myPeripheral, this.discoverCharacteristicsObserver);
        peripheral.removeUpdateValueObserver(this.myPeripheral, this.updateValueObserver);
        this.myPeripheral = null;
    }

    onResume() {
        super.onResume();
        central.addStateObserver(this, this.stateObserver);
        central.addDiscoverObserver(this, this.discoverObserver);
        central.addConnectObserver(this, this.connectObserver);
        central.addDisconnectObserver(this, this.disconnectObserver);
        // ...
    }

    onPause() {
        super.onPause();

        central.removeStateObserver(this.stateObserver);
        central.removeDiscoverObserver(this.discoverObserver);
        central.removeConnectObserver(this.connectObserver);
        central.removeDisconnectObserver(this, this.disconnectObserver);

        central.stopScan();
        this.uninitMyPeripheral();
    }

}

export { BleHelper };
